package net.chrisrichardson.ec2deployer.applications

import net.chrisrichardson.ec2deployer.cluster.ClusterSpec
import net.chrisrichardson.ec2deployer.core.EC2Server
import net.chrisrichardson.ec2deployer.cluster.DatabaseTier
import net.chrisrichardson.ec2deployer.cluster.TerracottaTier
import net.chrisrichardson.ec2deployer.cluster.WebServerTier

class SpringSourceDmServer extends AbstractApplicationServer {

    static final String SPRING_SOURCE_DM_SERVER_HOME = "/var/lib/springsource-dm-server-1.0.1.RELEASE"
    
    public SpringSourceDmServer(ClusterSpec clusterSpec, EC2Server host, DatabaseTier databaseTier, TerracottaTier terracottaTier, WebServerTier webServerTier) {
		super(clusterSpec, host, databaseTier, terracottaTier, webServerTier);
    }


    public void startTomcat(DirectorySnapshot webAppBundle) {
		assert host.isRunning()
		databaseTier.grantAccessToClient(this)

        writeFile fileName: ".sapenv", contents: """
export JAVA_OPTS='${makeCatalinaOpts()}'
export JAVA_HOME=/usr/java/default
        """

       stopTomcat()

        assert webAppBundle == null
		clusterSpec.webApps.each{it.updateTomcat(this, clusterSpec.bucketPrefix)}

		writeFile fileName: "$SPRING_SOURCE_DM_SERVER_HOME/config/servletContainer.config",
                templateName: "/templates/springSourceApplicationPlatform/servletContainer.config",
                templateArgs: [jvmRoute: jvmRoute]

        terracottaTier.prepareClient host

        exec "(. .sapenv ; cd $SPRING_SOURCE_DM_SERVER_HOME; nohup bin/startup.sh)  < /dev/null > /dev/null 2>&1 &"
	}

	public void stopTomcat() {
        exec ". .sapenv; cd $SPRING_SOURCE_DM_SERVER_HOME; bin/shutdown.sh"
    }

    String getDeploymentDirectory() {
        return "$SPRING_SOURCE_DM_SERVER_HOME/pickup"
    }

    boolean supportsExplodedWars() {
        return false
    }

    int getPingTries() {
        return 20
    }

    int getRetryDelay() {
        return 20
    }

   void startService() {
    // TODO
  }

  void stopService() {
    // TODO
  }
}